<?php

namespace plugin\admin\app\model;

use DateTimeInterface;
use support\Model;


class Base extends Model
{
    /**
     * @var string
     */
    protected $connection = 'plugin.admin.mysql';

    /**
     * 格式化日期
     *
     * @param DateTimeInterface $date
     * @return string
     */
    protected function serializeDate(DateTimeInterface $date)
    {
        return $date->format('Y-m-d H:i:s');
    }

    public function getWhere($where)
    {
        $query = $this;

        foreach ($where as $key=>$val){
            if(!is_array($val)){
                $query = $query->where($key,$val);
            }elseif(isset($val['or'])){
                $query = $query->Where(function ($query) use($val){
                    foreach($val['or'] as $v){
                        $query = $query->orWhere(function ($query) use ($v){
                            foreach($v as $kk=>$vv){
                                if(is_array($vv)){
                                    $query = $this->customeWhere($query, $vv);
                                }else{
                                    $query = $query->where($vv);
                                }
                            }
                            return $query;
                        });
                    }

                });
            }else{
                $query = $this->customeWhere($query, $val);
            }
        }

        return $query;
    }

    protected function customeWhere($query, $val)
    {
        switch ($val[1]){
            case 'in':
                $query = $query->whereIn($val[0],$val[2]);
                break;
            case 'notin':
                $query = $query->whereNotIn($val[0],$val[2]);
                break;
            case 'between':
                $query = $query->whereBetween($val[0],$val[2]);
                break;
            case 'notbetween':
                $query = $query->whereNotBetween($val[0],$val[2]);
                break;
            case 'null':
                $query = $query->whereNull($val[0]);
                break;
            case 'notnull':
                $query = $query->whereNotNull($val[0]);
                break;
            case 'custom':
                $query = $query->whereRaw($val[0]);
                break;
            default:
                $query = $query->where([$val]);
        }

        return $query;
    }
}
